package com.echo.echovividlive.websocket;

import com.alibaba.fastjson.JSONObject;
import com.echo.echovividlive.domain.vo.ChatVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
public class ChatRoom implements WebSocketHandler {


    private static final Map<Integer,WebSocketSession> sessionMap = new ConcurrentHashMap<>();
    private static final Map<Integer, List<WebSocketSession>> waitMap = new ConcurrentHashMap<>();


//    @OnOpen
//    public void onOpen(Session session){
//
//        System.out.println("连接已建立..."+session.getId());
//    }
//
//    @OnMessage
//    public void onMessage(Session session,String message) throws IOException {
//        System.out.println("来自"+session.getId()+"的消息"+message);
//        session.getBasicRemote().sendText("发送: " + message);
//
//    }
//
//    @OnClose
//    public void onClose(Session session){
//        System.out.println(session.getId()+ "断开连接...");
//    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        Object o =  session.getAttributes().get("userId");
        Integer userId = (Integer) o;
        // 广播上线消息
        List<WebSocketSession> orDefault = waitMap.getOrDefault(userId, new ArrayList<>());
        for (WebSocketSession webSocketSession : orDefault) {
            if(webSocketSession.isOpen()) {
                webSocketSession.sendMessage(new TextMessage("对方上线了"));
            }
        }
        waitMap.remove(userId);
        sessionMap.put(Integer.parseInt(o.toString()),session);
        session.sendMessage(new TextMessage("你已成功进入聊天室"));
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        Object payload = message.getPayload();
        ChatVO bean = JSONObject.parseObject(payload.toString(), ChatVO.class);
        Integer userId = bean.getUserId();
        WebSocketSession webSocketSession = sessionMap.get(userId);
        if(webSocketSession==null){
            // 对方未上线先加入等待队列
            List<WebSocketSession> orDefault = waitMap.getOrDefault(userId, new ArrayList<>());
            orDefault.add(session);
            waitMap.put(userId,orDefault);
            session.sendMessage(new TextMessage("该用户暂未进入聊天频道"));
            return;
        }
        if(!webSocketSession.isOpen()){
            session.sendMessage(new TextMessage("该用户已退出聊天"));
        }
        webSocketSession.sendMessage(new TextMessage(JSONObject.toJSONString(bean)));
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {

    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        sessionMap.entrySet().removeIf(entry -> entry.getValue() == session);
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}
